﻿using BLL;
using DBUtility;
using Fleck;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;

namespace UtilityHelper
{
    /// <summary>
    /// 调度功能通讯的socket
    /// </summary>
    public class DDSockets
    {
        public int TotalLineNum = 5;
        private static volatile DDSockets instance = null;
        private WebSocketServer m_server;
        private List<IWebSocketConnection> m_allSockets;
        /// <summary>
        /// 
        /// </summary>
        private Thread m_Thread_1 = null;
        private Thread m_Thread_2 = null;
        private Thread m_Thread_3 = null;
        private Thread m_Thread_4 = null;
        private Thread m_Thread_5 = null;

        private string m_ddMsg_1 = string.Empty;
        private string m_ddMsg_2 = string.Empty;
        private string m_ddMsg_3 = string.Empty;
        private string m_ddMsg_4 = string.Empty;
        private string m_ddMsg_5 = string.Empty;

        private DateTime m_dd_time_1 = DateTime.Now;
        private DateTime m_dd_time_2 = DateTime.Now;
        private DateTime m_dd_time_3 = DateTime.Now;
        private DateTime m_dd_time_4 = DateTime.Now;
        private DateTime m_dd_time_5 = DateTime.Now;

        private bool m_dd_status_1 = true;
        private bool m_dd_status_2 = true;
        private bool m_dd_status_3 = true;
        private bool m_dd_status_4 = true;
        private bool m_dd_status_5 = true;

        public static DDSockets GetInstance()
        {
           
            if (instance == null)
            {
                CONST_DEFINE_WEB_BLL bll = new CONST_DEFINE_WEB_BLL();
                var Infos = bll.GetModelList(" Name='DBAddress'");
                if (Infos.Length > 0)
                {
                    try
                    {
                        string strIP = string.Format("ws://{0}:{1}", Infos[0].ValueOfName, 8191);
                        //strIP = "ws://127.0.0.1:8191";
                        instance = new DDSockets();
                        instance.m_server = new WebSocketServer(strIP);
                        instance.m_allSockets = new List<IWebSocketConnection>();
                        instance.StartServe();
                    }
                    catch (Exception ex)
                    {
 
                    }
                }
            }
            return instance; 
        }

        private void StartServe()
        {
            if (m_server != null)
            {
                if (m_server != null)
                {
                    m_server.Start(socket =>
                    {
                        socket.OnOpen = () =>
                        {    
                            
                            m_allSockets.Add(socket);
                        };
                        socket.OnClose = () =>
                        {          
                        };
                        socket.OnMessage = message =>
                        {
                            if (message == "dd_1")
                            {
                                m_dd_time_1 = DateTime.Now;
                            }
                            if (message == "dd_2")
                            {
                                m_dd_time_2 = DateTime.Now;
                            }
                            if (message == "dd_3")
                            {
                                m_dd_time_3 = DateTime.Now;
                            }
                            if (message == "dd_4")
                            {
                                m_dd_time_4 = DateTime.Now;
                            }
                            if (message == "dd_5")
                            {
                                m_dd_time_5 = DateTime.Now;
                            }
                        };

                    });
                }
            }
        }

        public void SendMsg(string str)
        {
            foreach (var socket in m_allSockets)
            {
                if (socket != null)
                {
                    socket.Send(str);
                }
            }
        }

        public void StartSendDDMsg()
        {
            m_dd_status_1 = true;
            m_dd_status_2 = true;
            m_dd_status_3 = true;
            m_dd_status_4 = true;
            m_dd_status_5 = true;

            m_dd_time_1 = DateTime.Now;
            m_dd_time_2 = DateTime.Now;
            m_dd_time_3 = DateTime.Now;
            m_dd_time_4 = DateTime.Now;
            m_dd_time_5 = DateTime.Now;

            if (m_Thread_1 == null)
            {
                m_Thread_1 = new Thread(() =>
                {
                    while (m_dd_status_1)
                    {
                        SendMsg(DataTableToStr(1));
                        if (m_dd_time_1.AddSeconds(30) < DateTime.Now)
                        {
                            m_dd_status_1 = false;
                            m_Thread_1 = null;
                        }
                        Thread.Sleep(1000);
                    }

                });
                m_Thread_1.Start();
            }
            if (m_Thread_2 == null)
            {
                m_Thread_2 = new Thread(() =>
                {
                    while (m_dd_status_2)
                    {
                        SendMsg(DataTableToStr(2));
                        if (m_dd_time_2.AddSeconds(30) < DateTime.Now)
                        {
                            m_dd_status_2 = false;
                            m_Thread_2 = null;
                        }
                        Thread.Sleep(1000);
                    }

                });
                m_Thread_2.Start();
            }
            if (m_Thread_3 == null)
            {
                m_Thread_3 = new Thread(() =>
                {
                    while (m_dd_status_3)
                    {
                        SendMsg(DataTableToStr(3));
                        if (m_dd_time_3.AddSeconds(30) < DateTime.Now)
                        {
                            m_dd_status_3 = false;
                            m_Thread_3 = null;
                        }
                        Thread.Sleep(1000);
                    }

                });
                m_Thread_3.Start();
            }
            if (m_Thread_4 == null)
            {
                m_Thread_4 = new Thread(() =>
                {
                    while (m_dd_status_4)
                    {
                        SendMsg(DataTableToStr(4));
                        if (m_dd_time_4.AddSeconds(30) < DateTime.Now)
                        {
                            m_dd_status_4 = false;
                            m_Thread_4 = null;
                        }
                        Thread.Sleep(1000);
                    }

                });
                m_Thread_4.Start();
            }
            if (m_Thread_5 == null)
            {
                m_Thread_5 = new Thread(() =>
                {
                    while (m_dd_status_5)
                    {
                        SendMsg(DataTableToStr(5));
                        if (m_dd_time_5.AddSeconds(30) < DateTime.Now)
                        {
                            m_dd_status_5 = false;
                            m_Thread_5 = null;
                        }
                        Thread.Sleep(1000);
                    }

                });
                m_Thread_5.Start();
            }
        }

        private string DataTableToStr(int lineNum)
        {
            DataTable dt = GetData(lineNum);
            dt = ReDataTable(dt);

            DataTable dHead = ReBulidHeadTable(lineNum);

            JsonDataEntity entity = new JsonDataEntity();
            entity.Mark = "ZXZT";
            entity.Msg = dt;
            entity.HeadMsg = dHead;
            entity.LineNum = lineNum;

            string str = JsonConvert.SerializeObject(entity);

            return str;
        }

        private DataTable GetTableHeadMsg(int lineNum)
        {
            DataTable dt = new DataTable();
            string sql = string.Format("SELECT STA_ID,STA_NAME FROM  INSPECTION_LINE_INFO WHERE LINE_ID = {0}", lineNum);
            DbHelper.GetTable(sql, ref dt);
            return dt;
        }

        private DataTable ReBulidHeadTable(int lineNum)
        {
            DataTable dt = GetTableHeadMsg(lineNum);

            DataTable dTable = new DataTable();
            dTable.Columns.Add("STA_ID", typeof(int));
            dTable.Columns.Add("STA_NAME", typeof(string));

            int i = 1;
            while (dTable.Rows.Count <= dt.Rows.Count && i < 10)
            {
                DataRow dr = dTable.NewRow();
                foreach (DataRow item in dt.Rows)
                {
                    if (Convert.ToInt32(item["STA_ID"]) == i)
                    {
                        dr["STA_ID"] = item["STA_ID"];
                        dr["STA_NAME"] = item["STA_NAME"];
                        dTable.Rows.Add(dr);
                    }
                }
                i++;

            }

            return dTable;
        }

        private DataTable GetData(int lineNum)
        {
            DataTable dt = new DataTable();
            string strSql = "select ID,HPHM,HPZL,HPZLDH,JCXH,ISNULL(GWBH,-1) AS GWBH,JCZT_STATUS,JYXM FROM VEHICLE_DISPATCH where JCZT_STATUS = 2 and jcxh is not null order by JCXH ASC";
            strSql = string.Format("SELECT DISTINCT A.JCLSH,A.HPHM,ISNULL(A.JCZT_STATUS,0) AS JCZT_STATUS, A.AJLSH,ISNULL(A.GWBH,0) AS GWBH,A.GXRQ,B.IsSuc,C.IsSuc," +
            "CASE WHEN ISNULL(B.IsSuc,0) = 1 AND ISNULL(C.IsSuc,0) = 0 THEN '是' ELSE '否' END AS IS_LOGIN," +
            "CASE WHEN ISNULL(C.IsSuc,0) = 1 THEN '是' ELSE '否' END AS IS_UPLOAD "
            + "FROM VEHICLE_DISPATCH A"
            + " LEFT JOIN NET_AJ_JK_RESULT B ON B.LWLSH = A.AJLSH AND B.JKName = '18c66'"
            + " LEFT JOIN NET_JK_RESULT C ON C.JCLSH = A.JCLSH AND C.JKID = '18C62'"
            + " WHERE A.JCXH = {0} AND CONVERT(VARCHAR(10),A.GXRQ,120) = CONVERT(VARCHAR(10),GETDATE(),120)"
            + " ORDER BY A.GXRQ DESC", lineNum);
            DbHelper.GetTable(strSql, ref dt);
            return dt;
        }

        private DataTable ReDataTable(DataTable dt)
        {

            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("OnLine", typeof(int));
            Dictionary<int, int> dic = new Dictionary<int, int>();
            List<int> list = new List<int>();
            int j = 0;
            int i = 1;
            for (int t = 0; t < dt.Rows.Count; t++)
            {
                dt.Rows[t]["ID"] = i;

                if (Convert.ToInt32(dt.Rows[t]["JCZT_STATUS"]) == 2 && t == 0)
                {
                    dt.Rows[t]["OnLine"] = 1;
                    list.Add(Convert.ToInt32(dt.Rows[t]["GWBH"]));

                }
                else if (Convert.ToInt32(dt.Rows[t]["JCZT_STATUS"]) == 2 && t > 0)
                {
                    if (list.Contains(Convert.ToInt32(dt.Rows[t]["GWBH"])))
                    {
                        dt.Rows[t - 1]["OnLine"] = 0;
                    }
                    dt.Rows[t]["OnLine"] = 1;
                }
                else
                {
                    dt.Rows[t]["OnLine"] = 0;
                }

                i++;
            }
            return dt;
        }

        public class JsonDataEntity
        {
            public string Mark
            {
                get;
                set;
            }

            public Object Msg
            {
                get;
                set;
            }

            public Object HeadMsg
            {
                get;
                set;
            }

            public int LineNum
            {
                get;
                set;
            }
        }

    }
}
